package vn.training.view.bean;

import java.util.Map;

import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.context.AdfFacesContext;

import oracle.binding.BindingContainer;

import oracle.ui.pattern.dynamicShell.Tab;
import oracle.ui.pattern.dynamicShell.TabContext;

import vn.training.view.util.JSFUtils;

public class BaseFlowBean {
    public BaseFlowBean() {
        super();
    }
    
    protected void launchActivity(String title, String taskflowId,
                                  Map<String, Object> parameterMap,
                                  boolean newTab) {
        try {
            TabContext tabContext = getTabContext();
            if (newTab) {
                tabContext.addTab(title, taskflowId, parameterMap);

            } else {
                tabContext.addOrSelectTab(title, taskflowId, parameterMap);
            }
        } catch (TabContext.TabOverflowException toe) {
            // causes a dialog to be displayed to the user saying that there are
            // too many tabs open - the new tab will not be opened...
            toe.handleDefault();
        }
    }
    
    protected void launchActivity(String title, String taskflowId, boolean newTab) {
        launchActivity(title, taskflowId, null, newTab);
    }
    
    public BindingContainer getBindings() {
        return (BindingContainer)JSFUtils.resolveExpression("#{bindings}");
    }

    public void setCurrentTabDirty(boolean dirty) {
        getTabContext().markCurrentTabDirty(dirty);
    }

    public void setCurrentTabClean() {
        setCurrentTabDirty(false);
    }

    public void setCurrentTabDirty() {
        setCurrentTabDirty(true);
    }

    public Map<String, Object> getPageFlowScope() {
        return AdfFacesContext.getCurrentInstance().getPageFlowScope();
    }
    
    public void closeCurrentTab(ActionEvent actionEvent) {
        closeCurrentTabAction();
    }

    public void closeCurrentTabAction() {
        getTabContext().removeCurrentTab();
    }

    public void closeEmployeeTab() {
        getTabContext().removeCurrentTab();
        getTabContext().setSelectedTabIndex(1);
    }

    public TabContext getTabContext() {
        return TabContext.getCurrentInstance();
    }


    protected void updateCurrentTabTitle(String title) {
        getCurrentTab().setTitle(title);
    }

    protected Tab getCurrentTab() {
        TabContext tabContext = getTabContext();
        return tabContext.getTabs().get(tabContext.getSelectedTabIndex());
    }
    
    /*
    public void refreshPage() {
        FacesContext fctx = FacesContext.getCurrentInstance();
        String refreshpage = fctx.getViewRoot().getViewId();
        ViewHandler ViewH = fctx.getApplication().getViewHandler();
        UIViewRoot UIV = ViewH.createView(fctx, refreshpage);
        UIV.setViewId(refreshpage);
        fctx.setViewRoot(UIV);
    }*/
}
